/**
 * 
 */
package cc.dogtailflower.framework.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet处理类
 * @author cc
 *
 */
public class ServletHandler {

	/*
	 * 每个线程独自一份ServletHandler实例
	 */
	private static final ThreadLocal<ServletHandler> SERVLET_HANDLER_POOL = new ThreadLocal<ServletHandler>();
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public ServletHandler(HttpServletRequest request, HttpServletResponse response) {
		super();
		this.request = request;
		this.response = response;
	}
	
	/*
	 * 初始化
	 */
	public static void init(HttpServletRequest request, HttpServletResponse response){
		SERVLET_HANDLER_POOL.set(new ServletHandler(request,response));
	}
	
	/*
	 * 销毁 当前线程的对象
	 */
	public static void destroy(){
		SERVLET_HANDLER_POOL.remove();
	}
	
	/*
	 * 获取 request 对象
	 */
	public static HttpServletRequest getRequest(){
		return SERVLET_HANDLER_POOL.get().request;
	}
	
	/*
	 * 获取 response 对象
	 */
	public static HttpServletResponse getResponse(){
		return SERVLET_HANDLER_POOL.get().response;
	}
	
	/*
	 * 获取 Session 对象
	 */
	public static HttpSession getSession(){
		return getRequest().getSession();
	}
	
	/*
	 * 将属性放入 Request 中
	 */
	public static void setRequestAttribute(String key,Object value){
		getRequest().setAttribute(key, value);
	}
	
	/*
	 * 从 Request 中获取属性
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getRequestAttribute(String key){
		return (T)getRequest().getAttribute(key);
	}
	
	/*
	 * 从 Request 中移除属性
	 */
	public static void removeRequestAttribute(String key){
		getRequest().removeAttribute(key);
	}
	
	/*
	 * 重定向
	 */
	public static void sendRedirect(String location){
		try{
			getResponse().sendRedirect(getRequest().getContextPath() + location);
		}catch(IOException e){
			e.printStackTrace();
			
		}
	}
	
	/*
	 * 将 属性放入 Session 中
	 */
	public static void setSessionAttribute(String key,Object value){
		getSession().setAttribute(key,value);
	}
	
	/*
	 * 从 Session 中获取属性
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(String key){
		return (T)getRequest().getSession().getAttribute(key);
	}
	
	/*
	 * 从 Session 中移除属性
	 */
	public static void removeSessionAttribute(String key){
		getRequest().getSession().removeAttribute(key);
	}
	
	/*
	 * 使 Session 失效
	 */
	public static void invalidateSession(){
		getRequest().getSession().invalidate();
	}
}
